/**
 * Created by XiMing on 2015/6/21.
 */
var nodemailer = require('nodemailer');
var co = require('co'),
    request = require('request'),
    schedule = require("node-schedule"),
    cheerio  = require('cheerio'),
    db = require('./db');
var transporter = nodemailer.createTransport({
    service: 'qq',
    auth: {
        user: '807754634@qq.com',
        pass: 's1308118099'
    }
});
var email = require("emailjs/email");
var server = email.server.connect({
    user: "a1308118099@163.com",
    password: "s807754634",
    host: "smtp.163.com",
    ssl: true
});

var sendemail = function(title,link,id){
    //var mailOptions = {
    //    from: 'AQ最厉害了<a1308118099@163.com>', // sender address
    //    to: 'ximing@yeanzhi.cn,2296261055@qq.com',// list of receivers
    //    subject: title, // Subject line
    //    html: '<a href="http://ssdut.dlut.edu.cn'+link+'"><p>'+title+'</p></a>'// plaintext body
    //};
    //transporter.sendMail(mailOptions, function(error, info){
    //    if(error){
    //        return console.log(error);
    //    }else{
    //        console.log('Message sent: ' + info.response);
    //        db.zhouzhi.find({where:{id:id}}).then(function(p){
    //            p.send_email = 0;
    //            p.save().then(function(p){});
    //        });
    //    }
    //});
    server.send({
        text: title,
        from: "AQ最厉害了 <a1308118099@163.com>",
        to: 'ximing@yeanzhi.cn,2296261055@qq.com',
        subject: title,
        attachment: [
            {
                data: '<html><body><a href="http://ssdut.dlut.edu.cn' + link + '"><p>' + title + '</p></a></body> </html>',
                alternative: true
            }
        ]
    }, function (err, message) {
        if (err) {
            return console.log(error);
        } else {
            db.zhouzhi.find({
                where: {
                    id: id
                }
            }).then(function (p) {
                p.send_email = 0;
                p.save().then(function (p) {
                });
            });
        }
    });
};

var rule = new schedule.RecurrenceRule();
var times = [];
for(var i=1; i<60; i++){
    if(i%2==0){
        times.push(i);
    }
}
rule.minute = times;
var j = schedule.scheduleJob(rule, function(){
    db.zhouzhi.findAll({where:{send_email:1}}).then(function(p){
        var len = p.length;
        for(var i=0;i<len;i++){
            (function(i){
                sendemail(p[i].title,p[i].link,p[i].id);
            }(i))
        }
    });
});